package com.sunfeng.chap2.p17;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2021/10/11  9:34
 */
public class FileLockAPI_1 {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\nio\\a.txt");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();

        System.out.println(fileChannel.hashCode());

        FileLock lock = fileChannel.lock(1, 10, true);

        System.out.println("A position=" + lock.position() + " size =" + lock.size() + " isValid=" + lock.isValid()
                + " isShared=" + lock.isShared() + " channel.hashCode=" + lock.channel().hashCode() + "acquiredBy=" + lock.acquiredBy().hashCode());
        lock.release();
        lock = fileChannel.lock(1, 10, true);
        System.out.println("B position=" + lock.position() + " size =" + lock.size() + " isValid=" + lock.isValid()
                + " isShared=" + lock.isShared() + " channel.hashCode=" + lock.channel().hashCode() + "acquiredBy=" + lock.acquiredBy().hashCode());
        lock.close();;
        fileChannel.close();
        System.out.println("C position=" + lock.position() + " size =" + lock.size() + " isValid=" + lock.isValid()
                + " isShared=" + lock.isShared() + " channel.hashCode=" + lock.channel().hashCode() + "acquiredBy=" + lock.acquiredBy().hashCode());
    }
}
